from project.utils.role import project_role_permissions
from project.models import ProjectRole
from pms.common.views import PermissionDeny
from pms.common.utils import has_one_of_permissions


def has_project_permissions(pid, uid, permissions):
    role = ProjectRole.objects.get(pid__id=pid, participate__uid=uid)
    pids = project_role_permissions(role)
    if 1 in pids:  # User has all project permissions.
        return True
    for p in permissions:
        if p not in pids:
            return False
    return True


def has_one_of_project_permissions(pid, uid, permissions):
    role = ProjectRole.objects.get(pid__id=pid, participate__uid=uid)
    pids = project_role_permissions(role)
    if 1 in pids:  # User has all project permissions.
        return True
    else:
        return has_one_of_permissions(permissions, pids)


def assert_project_permissions(pid, uid, permissions):
    if not has_project_permissions(pid, uid, permissions):
        raise PermissionDeny


def assert_one_of_project_permissions(pid, uid, permissions):
    if not has_one_of_project_permissions(pid, uid, permissions):
        raise PermissionDeny
